<template>
  <el-dialog v-model="visible" :title="dialogTitle" @close="close" :width="dynamicWidth">
    <!-- <div class="flex-center c-warning mb-12px">目录下只能有菜单、菜单下只能有按钮</div> -->

    <el-form :model ref="modelRef" :rules label-width="80px" class="crud-action-form" :labelPosition>
      <el-row :gutter="16">
        <el-col :span="24">
          <el-form-item label="上级菜单" prop="parentId">
            <el-tree-select v-model="model.parentId" check-strictly node-key="id" :data="parentList" :props="{ label: 'title' }" place="请选择上级菜单" clearable> </el-tree-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="菜单类型" prop="type">
            <el-radio-group v-model.trim="model.type" size="small">
              <el-radio label="目录" value="M" border />
              <el-radio label="菜单" value="C" border />
              <el-radio label="按钮" value="F" border />
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="24" v-if="model.type !== 'F'">
          <el-form-item label="菜单图标" prop="icon">
            <el-popover placement="bottom-start" width="460" trigger="click" @show="iconSelectRef?.reset">
              <EpIconSelect ref="iconSelectRef" :active-icon="model.icon" @selected="selectMenuIcon" />
              <template #reference>
                <el-input v-model.trim="model.icon" placeholder="请选择菜单图标" readonly>
                  <template #prefix> <SvgIcon :name="`${model.icon ? model.icon : 'Search'}`" /> </template>
                </el-input>
              </template>
            </el-popover>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="菜单名称" prop="title">
            <el-input v-model.trim="model.title" placeholder="请输入菜单名称"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="显示排序" prop="order">
            <el-input-number v-model.number="model.order" controls-position="right" />
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="model.type !== 'F'">
          <el-form-item label="路由地址" prop="path">
            <el-input v-model.trim="model.path" placeholder="请输入路由地址" />
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="model.type === 'C'">
          <el-form-item label="组件路径" prop="component">
            <el-input v-model.trim="model.component" placeholder="请输入组件路径" />
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="model.type === 'F'">
          <el-form-item label="权限字符" prop="permission">
            <el-input v-model.trim="model.permission" placeholder="请输入权限标识" maxlength="100" />
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="model.type !== 'F'">
          <el-form-item label="显示状态" prop="visible">
            <el-radio-group v-model="model.visible" size="small">
              <el-radio label="显示" :value="1" border />
              <el-radio label="隐藏" :value="0" border />
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="菜单状态" prop="status">
            <el-radio-group v-model="model.status" size="small">
              <el-radio label="正常" :value="1" border />
              <el-radio label="停用" :value="0" border />
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="model.type !== 'F'">
          <el-form-item label="一级路由" prop="full">
            <el-radio-group v-model="model.full" size="small">
              <el-radio label="是" :value="1" border />
              <el-radio label="否" :value="0" border />
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="model.type === 'C'">
          <el-form-item label="缓存组件" prop="isCache">
            <el-radio-group v-model="model.isCache" size="small">
              <el-radio label="是" :value="1" border />
              <el-radio label="否" :value="0" border />
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="flex-center">
        <ep-button type="info" @click="close" svg-icon="Close">取消</ep-button>
        <ep-button type="primary" @click="submit" svg-icon="Save">确认</ep-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
defineOptions({ name: 'MenuActionDialog' })
import { GlobalComponents } from 'vue'
import { TipModal } from '@/utils'
import { MenuRequest } from '@/api/system/menu.request'
import type { FormInstance, FormRules } from 'element-plus'

/** 接收父组件传递的事件 */
const emits = defineEmits(['getList'])

const appStore = useAppStore()

const labelPosition = computed(() => (appStore.isDesktop ? 'left' : 'top'))
const iconSelectRef = ref<InstanceType<GlobalComponents['EpIconSelect']>>() // 图标选择组件实例
const visible = ref<boolean>(false)
const model = ref({} as MenuType.Entity)
const modelRef = ref<FormInstance>()
const parentList = ref<MenuType.TreeEntity[]>([]) // 菜单下拉树选项
const isUpdate = computed(() => Reflect.has(model.value, 'id'))
const dialogTitle = computed(() => (isUpdate.value ? '更新菜单' : '添加菜单'))
const dynamicWidth = computed(() => (appStore.isDesktop ? `600px` : `calc(100% - 32px)`))
const submitSuccessMessage = computed(() => (isUpdate.value ? `数据修改成功` : `数据添加成功`))
const rules: FormRules<MenuType.Entity> = {
  path: { required: true, message: '路由地址不可为空', trigger: 'blur' },
  order: { required: true, message: '菜单顺序不能为空', trigger: 'blur' },
  title: { required: true, message: '菜单名称不可为空', trigger: 'blur' },
}

async function getParentList() {
  const data = await MenuRequest.findParentList()
  parentList.value = data
}

function selectMenuIcon(name: string) {
  model.value.icon! = name
}

function resetForm() {
  model.value = { status: 1, visible: 1, order: 1, type: 'M', full: 0, isCache: 0 } as unknown as MenuType.Entity
}

async function open(menu?: MenuType.Entity) {
  resetForm()
  await getParentList()
  const parentId = menu ? (menu.type === 'F' ? menu.parentId : menu.id) : '0'
  if (menu && menu.type === 'F') model.value.type = 'F'
  if (menu) model.value.order = menu.order + 1
  model.value.parentId = parentId
  visible.value = true
}

function close() {
  visible.value = false
  modelRef.value?.resetFields()
}

async function update(menuId: string) {
  await getParentList()
  model.value = await MenuRequest.findOneById({ menuId })
  visible.value = true
}

async function submit() {
  try {
    await modelRef.value?.validate()
    isUpdate.value ? await MenuRequest.update(model.value) : await MenuRequest.create(model.value)
    TipModal.msgSuccess(submitSuccessMessage.value)
    emits('getList')
    close()
  } catch (error) {}
}

defineExpose({ open, update })
</script>

<style lang="scss" scoped></style>
